import common_url from './common_url.js'
import CryptoJS from 'crypto-js';




const http = {
	get: function(url, params) {
		return new Promise((resolve, reject) => {
			try {
				//登录时间超过30min清除缓存记录
				if (uni.getStorageSync('loginTime')) {
					let lastLoginTime = uni.getStorageSync('loginTime')
					let nowTime = new Date().getTime()
					let t = parseInt((nowTime - lastLoginTime) / 60000)
					//console.log('t',t)
					if (t > 120) { //二小时过期
						uni.showToast({
							title: "登录超时,重新登录",
							icon: "none",
							duration: 1500
						});
						uni.clearStorageSync();
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}, 1000)
						return
					}
				}
				let token = uni.getStorageSync('token') || '';
				let header = {
					'token': token,
					'content-type': 'application/x-www-form-urlencoded'
				}

				uni.request({
					url: common_url + url,
					data: params,
					header: header,
					method: 'GET',
					success: (res) => {
						if (res.statusCode == 200) {
							if (res.data.code == 401) {
								uni.clearStorageSync();
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 1000
								})
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}, 1000)
								return
							}
							resolve(res.data)
						}
					}
				})
			} catch (err) {
				reject(err)
			}
		})
	},
	post: function(url, params) {
		return new Promise((resolve, reject) => {
			try {
				//登录时间超过30min清除缓存记录
				if (uni.getStorageSync('loginTime')) {
					let lastLoginTime = uni.getStorageSync('loginTime')
					let nowTime = new Date().getTime()
					let t = parseInt((nowTime - lastLoginTime) / 60000)
					if (t > 120) { //二小时过期
						uni.showToast({
							title: "登录超时,重新登录",
							icon: "none",
							duration: 1500
						});
						uni.clearStorageSync();
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}, 1000)
						return
					}
				}

				let token = uni.getStorageSync('token') || '';
				let header = {
					'token': token,
					'content-type': 'application/json;charset=UTF-8'
				}


				function generateSign(params, timestamp) {
					// 1. 取出 timestamp 值并进行 MD5 得到 $md5
					const md5Timestamp = CryptoJS.MD5(timestamp.toString()).toString();

					// 2. 参数按照 key 排序（升序）
					const sortedKeys = Object.keys(params).sort();
					const paramStr = sortedKeys.map(k => `${k}=${params[k]}`).join('&');

					// 3. 左右拼接 $md5
					const signedStr = `${md5Timestamp}${paramStr}${md5Timestamp}`;

					// 4. 再次 MD5 得到最终签名
					const sign = CryptoJS.MD5(signedStr).toString();

					return sign;
				}


				let timestamp = Math.floor(Date.now() / 1000);
				let sign = generateSign(params, timestamp)
				params = {
					...params,
					timestamp: timestamp,
					sign: sign
				};
				uni.request({
					url: common_url + url,
					data: params,
					header: header,
					method: 'POST',
					success: (res) => {
						if (res.statusCode == 200) {
							if (res.data.code == -3) {
								uni.clearStorageSync();
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 1000
								})
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}, 1000)
								return
							}
							resolve(res.data)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: "none",
								duration: 1500
							});
						}
					},
					fail: (error) => {
						console.log(error)
					}
				})
			} catch (err) {
				reject(err)
			}
		})
	},
	//多图上传普通
	uploads: function(params) {
		return new Promise((resolve, reject) => {
			try {
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						let tempFilePath = res.tempFilePaths;
						console.log(tempFilePath, 'tempFilePath', res)
						let token = uni.getStorageSync('token') || '';
						let header = {
							'token': token,
							// 'content-type': 'application/x-www-form-urlencoded'
						}
						params = {
							...params,
							type: 'comment'
						}
						let imgs = []
						for (let i = 0, len = tempFilePath.length; i < len; i++) {
							uni.uploadFile({
								url: common_url + '/app/communals/uploadImage',
								filePath: tempFilePath[i],
								name: 'file',
								formData: params,
								header: header,
								success: (res1) => {
									let data = JSON.parse(res1.data)

									if (res1.statusCode == 200 && data.code ==
										0) {
										let res = data.data.path

										imgs.push(res)

										if (imgs.length == tempFilePath
											.length) {
											resolve(imgs)
										}
									} else {
										uni.showToast({
											title: res1.data.msg,
											icon: "none",
											duration: 1500
										});
									}
								}
							});
						}
					}
				});
			} catch (e) {
				reject(e)
			}
		})
	},
	//单图上传普通
	uploadone: function(params) {
		return new Promise((resolve, reject) => {
			try {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						let tempFilePath = res.tempFilePaths[0];
						let token = uni.getStorageSync('token') || '';
						let header = {
							'token': token,
							'content-type': 'application/x-www-form-urlencoded'
						}
						params = {
							...params,
							type: 'comment'
						}
						uni.uploadFile({
							url: common_url + '/app/communals/uploadImage',
							filePath: tempFilePath,
							name: 'file',
							formData: params,
							header: header,
							success: (res1) => {
								let data = JSON.parse(res1.data)
								console.log(data, 'data')
								if (res1.statusCode == 200 && data.code == 0) {
									let res = data.data.path
									resolve(res)
								} else {
									uni.showToast({
										title: res1.data.msg,
										icon: "none",
										duration: 1500
									});
								}
							}
						});
					}
				});
			} catch (e) {
				reject(e)
			}
		})
	},
	//视频上传普通
	uploadone2: function(params) {
		return new Promise((resolve, reject) => {
			try {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					mediaType: ['video'],
					success: (res) => {
						let tempFilePath = res.tempFilePaths[0];
						let token = uni.getStorageSync('token') || '';
						let header = {
							'token': token,
							'content-type': 'application/x-www-form-urlencoded'
						}
						uni.uploadFile({
							url: common_url + '/api/common/upload',
							filePath: tempFilePath,
							name: 'file',
							formData: params,
							header: header,
							success: (res1) => {
								let data = JSON.parse(res1.data)
								console.log(data, 'data')
								if (res1.statusCode == 200 && data.code == 1) {
									let res = data.data.url
									resolve(res)
								} else {
									uni.showToast({
										title: res1.data.msg,
										icon: "none",
										duration: 1500
									});
								}
							}
						});
					}
				});
			} catch (e) {
				reject(e)
			}
		})
	}
}

export default http;